package com.pig4cloud.pig.module.controller.setMeal;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.OrderUtil;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.setMeal.SetMealQrcode;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.setMeal.ISetMealQrcodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 套餐的 小区二维码Controller
 *
 * @author ruoyi
 * @date 2022-06-06
 */
@Validated
@Api(value = "套餐的小区二维码控制器", tags = {"套餐的 小区二维码管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/meal/qrCode")
public class SetMealQrcodeController {

    private final ISetMealQrcodeService setMealQrCodeService;
	private final IEstateService estateService;

//	@Value("${ruoyi.imgUrl}")
//	private String imgUrl;

	@Value("${ruoyi.imgUrlOss}")
	private String imgUrlOss;

	@Value("${ruoyi.profile}")
	private String uploadPath;
    /**
     * 查询套餐的 小区二维码列表
     */
    @ApiOperation("查询套餐的 小区二维码列表")
    @PreAuthorize("@pms.hasPermission('module:mealQrCode:list')")
    @GetMapping("/list")
    public TableDataInfo<SetMealQrcode> list(@Validated SetMealQrcode setMealQrcode) {
        QueryWrapper<SetMealQrcode> qw = new QueryWrapper<>();
        if(setMealQrcode.getMealId()!=null){
        	qw.eq("meal_id", setMealQrcode.getMealId());
		}
        TableDataInfo<SetMealQrcode> td = PageUtils.buildDataInfo(setMealQrCodeService.page(PageUtils.buildPage(),qw));
        List<SetMealQrcode> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
			for (SetMealQrcode mealQrcode : list){
				if(StrUtil.isNotEmpty(mealQrcode.getQrCode())){
					mealQrcode.setQrCode(imgUrlOss + mealQrcode.getQrCode());
				}
			}
		}
        return td;
    }

    /**
     * 获取套餐的 小区二维码详细信息
     */
    @ApiOperation("获取套餐的 小区二维码详细信息")
    @PreAuthorize("@pms.hasPermission('module:mealQrCode:query')")
    @GetMapping("/{id}")
    public R<SetMealQrcode> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        SetMealQrcode setMealQrcode = setMealQrCodeService.getById(id);
        return R.ok(setMealQrcode);
    }

    /**
     * 新增套餐的 小区二维码
     */
    @ApiOperation("新增套餐的 小区二维码")
    @PreAuthorize("@pms.hasPermission('module:mealQrCode:add')")
    @SysLog("套餐的 小区二维码")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody SetMealQrcode setMealQrcode) {

		Estate estate = estateService.findById(setMealQrcode.getEstateId());
		if(estate!=null){
			setMealQrcode.setEstateName(estate.getEstateName());
		}
		setMealQrcode.setCodeNum(OrderUtil.getSetMealNo());
    	try{
//			SetMeal setMeal = setMealService.findById(setMealQrcode.getMealId());
			String qrCode = "";
			String content = "https://www.sdyuedou.com/wxmini/meal/getMeal?no=" + setMealQrcode.getCodeNum() + "&eid="+ setMealQrcode.getEstateId();
			String fileName = "meal_qr_" + setMealQrcode.getCodeNum()+"_" + setMealQrcode.getEstateId() + ".jpg";

			int upload_type = 0;//FileUploadUtils.TYPE_SET_MEAL;
			System.out.println("content:  "+ content);
			String img_key = "";//FileUploadUtils.getUploadPrefix(upload_type) + fileName;
			QRCodeUtilEx.createQrCodeImg(content, setMealQrcode.getEstateName() + " " + setMealQrcode.getCodeNum() ,
				null, uploadPath +"/"+img_key, true, fileName, upload_type);
			qrCode = img_key;
			setMealQrcode.setQrCode(qrCode);
		}catch (Exception e){
    		e.printStackTrace();
		}

        return R.okByRow(setMealQrCodeService.save(setMealQrcode) ? 1 : 0);
    }

    /**
     * 修改套餐的 小区二维码
     */
    @ApiOperation("修改套餐的 小区二维码")
    @PreAuthorize("@pms.hasPermission('module:mealQrCode:edit')")
    @SysLog("套餐的 小区二维码")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody SetMealQrcode setMealQrcode) {

		Estate estate = estateService.findById(setMealQrcode.getEstateId());
		if(estate!=null){
			setMealQrcode.setEstateName(estate.getEstateName());
		}
		if(StrUtil.isEmpty(setMealQrcode.getCodeNum())){
			setMealQrcode.setCodeNum(OrderUtil.getSetMealNo());
		}
        return R.okByRow(setMealQrCodeService.updateById(setMealQrcode) ? 1 : 0);
    }


	/**
	 * 重置二维码
	 */
	@SysLog("重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@pms.hasPermission('module:mealQrCode:edit')")
	public R<Void> resetQrCode(@RequestBody SetMealQrcode setMealQrcode) {
		if(setMealQrcode.getId()!=null){
			try{
				setMealQrcode = setMealQrCodeService.getById(setMealQrcode.getId());
				if(setMealQrcode != null){
//					SetMeal setMeal = setMealService.findById(setMealQrcode.getMealId());
					if(StrUtil.isEmpty(setMealQrcode.getCodeNum())){
						setMealQrcode.setCodeNum(OrderUtil.getSetMealNo());
					}
					String qrCode = "";
					String content = "https://www.sdyuedou.com/wxmini/meal/getMeal?no=" + setMealQrcode.getCodeNum() + "&eid="+ setMealQrcode.getEstateId();
					String fileName = "meal_qr_" + setMealQrcode.getCodeNum()+"_" + setMealQrcode.getEstateId() + ".jpg";

					int upload_type = 0;//FileUploadUtils.TYPE_SET_MEAL;
					System.out.println("content:  "+ content);
					String img_key = "";// FileUploadUtils.getUploadPrefix(upload_type) + fileName;
					QRCodeUtilEx.createQrCodeImg(content, setMealQrcode.getEstateName() + " " + setMealQrcode.getCodeNum() ,
						null, uploadPath +"/"+img_key, true, fileName, upload_type);
					qrCode = img_key;
					setMealQrcode.setQrCode(qrCode);
				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (setMealQrCodeService.updateById(setMealQrcode)) {
				return R.ok();
			}
		}
		return R.failed();
	}


	/**
     * 删除套餐的 小区二维码
     */
    @ApiOperation("删除套餐的 小区二维码")
    @PreAuthorize("@pms.hasPermission('module:mealQrCode:remove')")
    @SysLog("套餐的 小区二维码")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(setMealQrCodeService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
